package com.example.commonlib.httplib;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

import com.example.commonlib.httplib.bean.TokenBean;
import com.example.commonlib.httplib.utils.SerializableUtil;

import java.io.IOException;


/**
 * Create by xjs
 * _______date : 17/8/3
 * _______description:token工具帮助类
 */
public class TokenHelper {

    public final static String KEY_TOKEN = "KEY_TOKEN";

    private SharedPreferences sharedPreferences;

    private static TokenHelper tokenHelper;

    private TokenBean tokenBean = null;

    public static TokenHelper getInstance(Context context) {
        if (tokenHelper == null) {
            synchronized (TokenHelper.class) {
                if (tokenHelper == null) {
                    tokenHelper = new TokenHelper(context);
                }
            }
        }
        return tokenHelper;
    }

    @SuppressLint("WrongConstant")
    public TokenHelper(Context context) {
        sharedPreferences = context.getSharedPreferences("SharedPreferences",
                Context.MODE_PRIVATE | Context.MODE_APPEND);
    }

    public synchronized void putTokenBean(TokenBean bean) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String str = "";
        try {
            str = SerializableUtil.obj2Str(bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        editor.putString(KEY_TOKEN, str);
        editor.commit();

        tokenBean = bean;
    }

    public synchronized TokenBean getTokenBean() {
        if (tokenBean == null) {
            tokenBean = new TokenBean();

            //获取序列化数据
            String str = sharedPreferences.getString(TokenHelper.KEY_TOKEN, "");

            Object object = null;
            try {
                object = SerializableUtil.str2Obj(str);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (object != null) {
                tokenBean = (TokenBean) object;
            }
        }
        return tokenBean;
    }

    public synchronized void clearTokenBean() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_TOKEN, "");
        editor.commit();
        tokenBean = null;
    }

}
